﻿var show_fit = 0;
var show_full = 1;

// 移动模式
var move_mode = 0;
// 放大模式
var magnifier_mode = 1;
// 窗宽窗位模式
var HSL_mode = 2;

function init_load_image_text_info(container,imageContext, index) {
    var h = $(container).innerHeight();
    var w = $(container).innerWidth();

    var canvas = $("<canvas class='canvas_text' width='" + w + "px' height='" + h + "px' style='display:none' />"); //style='background-color:black';
    $(container).append(canvas);
    var context = canvas[0].getContext('2d');
    context.save();
    context.font = "italic small-caps bold 20px arial";
    var gradient = context.createLinearGradient(0, 0, w, 0);
    gradient.addColorStop("0", "magenta");
    gradient.addColorStop("0.5", "blue");
    gradient.addColorStop("1.0", "red");
    // 用渐变填色
    context.fillStyle = gradient;
    context.fillText("Hello World1!", 50, 50);
    context.fillText("Hello World2!", 50, 80);
    context.fillText("Hello World3!", 50, 110);
    context.fillText("Hello World4!", 50, 140);
    context.restore();

    imageContext.drawImage(canvas[0], 0, 0,w,h);
}

// 初始化加载图片
function init_load_images(context, index, w, h) {
    var img = new Image();
    img.src = imageData.img[index].src;
    $(img).bind("load", { index: index, img: img, context: context, w: w, h: h }, function (e) {
        var index = e.data.index;
        var img = e.target; //e.data.img;
        var context = e.data.context;
        var w = e.data.w;
        var h = e.data.h;

        var t1 = w / (imageData.img[index].width);
        var t2 = h / imageData.img[index].height;

        var nw, nh;
        if (t1 < t2) {
            nw = w;
            nh = imageData.img[index].height * t1;
        } else {
            nh = h;
            nw = imageData.img[index].width * t2;
        }

        var x = 0, y = 0;
        x = w / 2 - nw / 2;
        //y = h / 2 - nh / 2;

        imageData.img[index]["img"] = img;

        context.save();
        context.drawImage(img, 0, 0, imageData.img[index].width, imageData.img[index].height, x, y, nw, nh);
        context.restore();
        var showRect = {};
        showRect["ox"] = 0;
        showRect["oy"] = 0;
        showRect["ow"] = imageData.img[index].width;
        showRect["oh"] = imageData.img[index].height;
        showRect["sx"] = x;
        showRect["sy"] = y;
        showRect["sw"] = nw;
        showRect["sh"] = nh;
        showRect["rotate"] = 0; // 旋转
        imageData.img[index]["showRect"] = showRect;
    });
}

function set_load_image_mode(context, index, w, h, mode) {
    var t1 = w / (imageData.img[index].width);
    var t2 = h / (imageData.img[index].height);
    var nw, nh;
    if (mode == show_fit) {
        if (t1 < t2) {
            nw = w;
            nh = imageData.img[index].height * t1;
        } else {
            nh = h;
            nw = imageData.img[index].width * t2;
        }
    } else {
        nw = imageData.img[index].width;
        nh = imageData.img[index].height;
    }
    var x = w / 2 - nw / 2;
    if (x < 0) {
        x = 0;
    }
    var y = h / 2 - nh / 2;
    if (y < 0) {
        y = 0;
    }
    context.save();
    context.clearRect(0, 0, w, h);
    context.drawImage(imageData.img[index]["img"], 0, 0, imageData.img[index].width, imageData.img[index].height, x, y, nw, nh);
    context.restore();
    showImageText(context);

    imageData.img[index]["showRect"]["ox"] = 0;
    imageData.img[index]["showRect"]["oy"] = 0;
    imageData.img[index]["showRect"]["ow"] = imageData.img[index].width;
    imageData.img[index]["showRect"]["oh"] = imageData.img[index].height;
    imageData.img[index]["showRect"]["sx"] = x;
    imageData.img[index]["showRect"]["sy"] = y;
    imageData.img[index]["showRect"]["sw"] = nw;
    imageData.img[index]["showRect"]["sh"] = nh;
    imageData.img[index]["showRect"]["rotate"] = 0; // 旋转
}

function init_show_images(divId) {
    var countPerPage = config.showModeX * config.showModeY;
    config.totalPage = Math.floor(imageData.count / countPerPage) + ((imageData.count % countPerPage) != 0 ? 1 : 0);

    for (var pageIndex = 0; pageIndex < config.totalPage; pageIndex++) {
        var canvasDiv = $("#" + divId);
        var h = canvasDiv.innerHeight();
        var w = canvasDiv.innerWidth();
        var pageDiv = $("<div class='pageDiv' pageNo='pn" + pageIndex + "'/>");
        canvasDiv.append(pageDiv);
        pageDiv.css("width", w)
                   .css("height", h)
                   .css("background-color", "black")
                   .css("position", "absolute")
                   .css("top", 0)
                   .css("left", 0);
        if (pageIndex != 0) {
            pageDiv.css("display", "none");
        }

        for (var i = 0; i < config.showModeX; i++) {
            for (var j = 0; j < config.showModeY; j++) {
                var top = i * (h / config.showModeX);
                var left = j * (w / config.showModeY);
                var width = w / config.showModeY;
                var height = h / config.showModeX;
                var imgIndex = pageIndex * countPerPage + i * config.showModeY + j;

                var dx = "<div class='backgroundDiv' id='img" + imgIndex + "' style='position:absolute;top:" + top + "px;left:" + left + "px;width:" + (width - 2) + "px;height:" + (height - 2) + "px;' />";
                var d = $(dx);
                d.css("border", "1px solid white");
                pageDiv.append(d);

                if (imgIndex >= imageData.count) {
                    continue;
                }
                if (imgIndex == 0) {
                    d.css("border-color", "red")
                     .addClass("backgroundDivSelected");
                }

                var moveState = { "ox": 0, "oy": 0, "move": false };
                imageData.img[imgIndex]["moveState"] = moveState;

                // 点击后边框变红色
                d.click(function () {
                    $(".backgroundDiv").css("border-color", "white")
                                       .removeClass("backgroundDivSelected");
                    $(this).css("border-color", "red")
                           .addClass("backgroundDivSelected");
                });

                var canvas = $("<canvas class='canvas_image' width='" + d.innerWidth() + "px' height='" + d.innerHeight() + "px' style='background-color:black;'/>");
                d.append(canvas);
                var context = canvas[0].getContext('2d');
                init_load_images(context, imgIndex, d.innerWidth(), d.innerHeight());
                // 文字
                init_load_image_text_info(d,context, imgIndex);

                d.bind("mousedown", { index: imgIndex }, function (e) {
                    var index = e.data.index;
                    imageData.img[index]["moveState"]["ox"] = e.screenX;
                    imageData.img[index]["moveState"]["oy"] = e.screenY;
                    imageData.img[index]["moveState"]["move"] = true;
                }).bind("mousemove", { index: imgIndex, context: context, canvas: canvas }, function (e) {
                    var index = e.data.index;
                    var context = e.data.context;
                    var canvas = e.data.canvas;
                    if (!imageData.img[index].moveState.move) {
                        return;
                    }

                    var offx = e.screenX - imageData.img[index]["moveState"]["ox"];
                    var offy = e.screenY - imageData.img[index]["moveState"]["oy"];


                    context.save();
                    context.clearRect(0, 0, $(this).innerWidth(), $(this).innerHeight());

                    if (config.workMode == move_mode) {
                        imageData.img[index]["moveState"]["ox"] = e.screenX;
                        imageData.img[index]["moveState"]["oy"] = e.screenY;
                        switch (imageData.img[index]["showRect"]["rotate"]) {
                            case 0:
                                imageData.img[index].showRect.sx += offx;
                                imageData.img[index].showRect.sy += offy;
                                break;
                            case -3:
                            case 1:
                                imageData.img[index].showRect.sx += offy;
                                imageData.img[index].showRect.sy -= offx;
                                context.rotate(90 * Math.PI / 180);
                                break;
                            case -2:
                            case 2:
                                imageData.img[index].showRect.sx -= offx;
                                imageData.img[index].showRect.sy -= offy;
                                context.rotate(180 * Math.PI / 180);
                                break;
                            case -1:
                            case 3:
                                imageData.img[index].showRect.sx -= offy;
                                imageData.img[index].showRect.sy += offx;
                                context.rotate(270 * Math.PI / 180);
                                break;
                        }
                        context.drawImage(
                            imageData.img[index].img,
                            imageData.img[index].showRect.ox, imageData.img[index].showRect.oy,
                            imageData.img[index].showRect.ow, imageData.img[index].showRect.oh,
                            imageData.img[index].showRect.sx, imageData.img[index].showRect.sy,
                            imageData.img[index].showRect.sw, imageData.img[index].showRect.sh);

                    } else if (config.workMode == HSL_mode) {
                        imageData.img[index].showRect.ww += offx;
                        imageData.img[index].showRect.wl += offy;

                        switch (imageData.img[index]["showRect"]["rotate"]) {
                            case 0:
                                break;
                            case -3:
                            case 1:
                                context.rotate(90 * Math.PI / 180);
                                break;
                            case -2:
                            case 2:
                                context.rotate(180 * Math.PI / 180);
                                break;
                            case -1:
                            case 3:
                                context.rotate(270 * Math.PI / 180);
                                break;
                        }

                        context.drawImage(
                            imageData.img[index].img,
                            imageData.img[index].showRect.ox, imageData.img[index].showRect.oy,
                            imageData.img[index].showRect.ow, imageData.img[index].showRect.oh,
                            imageData.img[index].showRect.sx, imageData.img[index].showRect.sy,
                            imageData.img[index].showRect.sw, imageData.img[index].showRect.sh);
                        //                        loadPattern(config.ww, config.wc, context, 
                        //                            imageData.img[index].showRect.sx, imageData.img[index].showRect.sy,
                        //                            imageData.img[index].showRect.sw, imageData.img[index].showRect.sh);
                        setHLS(imageData.img[index].showRect.ww, imageData.img[index].showRect.wl, context,
                            imageData.img[index].showRect.sx, imageData.img[index].showRect.sy,
                            imageData.img[index].showRect.sw, imageData.img[index].showRect.sh);
                    }
                    context.restore();
                    showImageText(context);
                }).bind("mouseup", { index: imgIndex }, function (e) {
                    var index = e.data.index;
                    imageData.img[index]["moveState"]["move"] = false;
                });
            }
        }
    }
}

var xxx;
var x1, x2;

function getPresentationValue(v, w, c) {
    var minv = c - Math.round(w / 2);
    if (v < minv) return 0;
    var maxv = c + Math.round(w / 2);
    if (v > maxv) return 255;
    var pv = Math.round(255 * (v - minv) / w);
    if (pv < 0) return 0;
    if (pv > 255) return 255;
    return pv;
}

function setHLS(ww, wl, context, x, y, w, h) {
    var imgData = context.getImageData(x, y, w, h);
    xxx = imgData;
    for (y = 0; y < h; y++) {
        for (x = 0; x < w; x++) {
            var i = (y * w + x) * 4;
            var v = imgData.data[i];
            var pv = getPresentationValue(v, ww, wl);
            imgData.data[i] = imgData.data[i + 1] = imgData.data[i + 2] = pv;
            imgData.data[i + 3] = 255;
        }
    }
    context.putImageData(imgData, x, y);
}

function doLayout(divId) {
    var countPerPage = config.showModeX * config.showModeY;
    config.currentPageNo=1;
    config.totalPage = Math.floor(imageData.count / countPerPage) + ((imageData.count % countPerPage) != 0 ? 1 : 0);
    var backgroundDivList = $("div.backgroundDiv");
    $("div.pageDiv").addClass("prepareRemove");

    for (var pageIndex = 0; pageIndex < config.totalPage; pageIndex++) {
        var canvasDiv = $("#" + divId);
        var h = canvasDiv.innerHeight();
        var w = canvasDiv.innerWidth();
        var pageDiv = $("<div class='pageDiv' pageNo='pn" + pageIndex + "'/>");
        canvasDiv.append(pageDiv);
        pageDiv.css("width", w)
                   .css("height", h)
                   .css("background-color", "black")
                   .css("position", "absolute")
                   .css("top", 0)
                   .css("left", 0);
        if (pageIndex != 0) {
            pageDiv.css("display", "none");
        }

        for (var i = 0; i < config.showModeX; i++) {
            for (var j = 0; j < config.showModeY; j++) {
                var top = i * (h / config.showModeX);
                var left = j * (w / config.showModeY);
                var width = w / config.showModeY;
                var height = h / config.showModeX;
                var imgIndex = pageIndex * countPerPage + i * config.showModeY + j;

                if (imgIndex >= imageData.count) {
                    var dx = $("<div style='position:absolute;top:" + top + "px;left:" + left + "px;width:" + (width - 2) + "px;height:" + (height - 2) + "px;border:1px solid white;' />");
                    pageDiv.append(dx);
                    continue;
                }

                var backgroundDiv = backgroundDivList[imgIndex];
                $(backgroundDiv).css("top", top)
                                .css("left", left)
                                .css("width", (width - 2))
                                .css("height", (height - 2))
                                .css("border-color", "white")
                                .removeClass("backgroundDivSelected");
                if (imgIndex == 0) {
                    $(backgroundDiv).css("border-color", "red")
                                    .addClass("backgroundDivSelected");
                }
                $(pageDiv).append($(backgroundDiv));

                $(backgroundDiv).find("canvas.canvas_image").each(function () {
                    var w = $(this).parent().innerWidth();
                    var h = $(this).parent().innerHeight();
                    $(this).attr("width", w)
                           .attr("height", h);

                    var x = w / 2 - imageData.img[imgIndex].showRect.sw / 2;
                    if (x < 0) {
                        x = 0;
                    }
                    imageData.img[imgIndex].showRect.sx = x;
                    var y = h / 2 - imageData.img[imgIndex].showRect.sh / 2;
                    if (y < 0) {
                        y = 0;
                    }
                    imageData.img[imgIndex].showRect.sy = y;

                    // ---------------------------------------------------------------------
                    imageData.img[imgIndex].showRect.ww = w;
                    imageData.img[imgIndex].showRect.wl = h;

                    var context = $(this)[0].getContext('2d');
                    context.save();
                    context.clearRect(0, 0, w, h);
                    changeRotate(context, imgIndex, w, h);
                    context.drawImage(
                        imageData.img[imgIndex].img,
                        imageData.img[imgIndex].showRect.ox, imageData.img[imgIndex].showRect.oy,
                        imageData.img[imgIndex].showRect.ow, imageData.img[imgIndex].showRect.oh,
                        imageData.img[imgIndex].showRect.sx, imageData.img[imgIndex].showRect.sy,
                        imageData.img[imgIndex].showRect.sw, imageData.img[imgIndex].showRect.sh);
                    context.restore();
                    showImageText(context);
                });
            }
        }
    }
    $(".prepareRemove").remove();
}

function changeRotate(context,index,w,h) {
    switch (imageData.img[index]["showRect"]["rotate"]) {
        case 0:
            imageData.img[index].showRect.sx = (w - imageData.img[index].showRect.sw) / 2;
            imageData.img[index].showRect.sy = (h - imageData.img[index].showRect.sh) / 2;
            break;
        case -3:
        case 1:
            imageData.img[index].showRect.sx = (h - imageData.img[index].showRect.sw) / 2;
            imageData.img[index].showRect.sy = 0 - (w + imageData.img[index].showRect.sh) / 2;
            context.rotate(90 * Math.PI / 180);
            break;
        case -2:
        case 2:
            imageData.img[index].showRect.sy = 0 - (h + imageData.img[index].showRect.sh) / 2;
            imageData.img[index].showRect.sx = 0 - (w + imageData.img[index].showRect.sw) / 2;
            context.rotate(Math.PI);
            break;
        case -1:
        case 3:
            imageData.img[index].showRect.sx = 0 - (h + imageData.img[index].showRect.sw) / 2;
            imageData.img[index].showRect.sy = (w - imageData.img[index].showRect.sh) / 2;
            context.rotate(270 * Math.PI / 180);
            break;
    }
}

function refreshAllCanvas() {
    $("canvas.canvas_image").each(function () {
        var id = $(this).parent().attr("id");
        var index = Number(id.replace(/img/, ""));

        var w = $(this).parent().innerWidth();
        var h = $(this).parent().innerHeight();

        var context = $(this)[0].getContext('2d');
        context.save();
        context.clearRect(0, 0, w, h);
        changeRotate(context, index, w, h);
        context.drawImage(
                        imageData.img[index].img,
                        imageData.img[index].showRect.ox, imageData.img[index].showRect.oy,
                        imageData.img[index].showRect.ow, imageData.img[index].showRect.oh,
                        imageData.img[index].showRect.sx, imageData.img[index].showRect.sy,
                        imageData.img[index].showRect.sw, imageData.img[index].showRect.sh);
        context.restore();
        showImageText(context);
    });
}

function showImageText(context) {
    if (config.showText) {
        var d = $(context.canvas).parent();
        var tw = d.innerWidth();
        var th = d.innerHeight();
        context.drawImage(d.children("canvas.canvas_text")[0], 0, 0, tw, th);
    }
}